package com.zmj.dubboannotation.consumermobile.inteceptor;

import com.zmj.commoncore.constant.CookieConstant;
import com.zmj.commoncore.utils.CookieUtil;
import com.zmj.commoncore.utils.JWTUtil;
import com.zmj.dubboannotation.serviceapi.enums.ResultEnum;
import com.zmj.dubboannotation.serviceapi.exception.MallAuthorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by: meijun
 * Date: 2018/10/21 8:26
 */
public class AuthorizationInteceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Cookie cookie = CookieUtil.get(request, CookieConstant.COOKIE_TOKEN);
        if(null != cookie) {
            String cookieValue = cookie.getValue();
            try {
                String  appUID = JWTUtil.getAppUID(cookieValue);
                if(StringUtils.isNotBlank(appUID)) {
                    String token = JWTUtil.createToken(appUID);
                    CookieUtil.set(response,CookieConstant.COOKIE_TOKEN,token, CookieConstant.COOKIE_EXPIRE);
                    return true;
                }
            }catch (Exception e) {
                throw new MallAuthorException(ResultEnum.NOT_TOKEN);
            }
        }
        return  false;
    }
}
